package com.iyao_app.mvp.register;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iyao_app.R;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.Register;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.mvp.completeinfo.CompleteInfoActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.CustomDialog;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.view.LetterSpacingTextView;
import com.iyaowoqu.base_library.constant.RegexConstants;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.RegexUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者 : 胡家兵
 * 时间 : 2017/11/9.
 */

public class RegisterActivity extends BaseActivity implements RegisterContract.View {
    private static final long MAX_COUNT_TIME = 60;
    RegisterContract.Presenter mPresenter;
    @BindView(R.id.et_login_account)
    EditText mEtLoginAccount;
    @BindView(R.id.et_login_password)
    EditText mEtLoginPassword;
    @BindView(R.id.et_message)
    EditText mEtMessage;
    @BindView(R.id.tv_send)
    LetterSpacingTextView mTvSend;
    @BindView(R.id.tv_fail)
    TextView mTvFail;
    @BindView(R.id.rl_root)
    RelativeLayout mRlRoot;
    private Bitmap bm;
    private boolean isSend = false;
    private CountDownTimer mTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_register);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ButterKnife.bind(this);
        initData();
        bm = BitmapFactory.decodeResource(this.getResources(), R.mipmap.bg_ditu_denglu);
        BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
        mRlRoot.setBackgroundDrawable(bd);
        new RegisterPresenter(this);
    }

    private void initData() {

        SpannableString s = new SpannableString(ResourcesUtils.getString(R.string.hint_password));
        AbsoluteSizeSpan textSize = new AbsoluteSizeSpan(11, true);
        s.setSpan(textSize, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mEtLoginPassword.setHint(s);

        mEtLoginAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEtLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEtMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEtMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    KeyboardUtils.hideSoftInput(mEtMessage);
                }

                return false;
            }
        });
    }

    @Override
    public void setPresenter(RegisterContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hidProgress() {

    }

    @OnClick({R.id.tv_send, R.id.tv_register, R.id.iv_back,R.id.rl_root1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_send:
                senMessage();
                break;
            case R.id.tv_register:
                check();

                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_root1:

                KeyboardUtils.hideSoftInput(this);
                break;
        }
    }


    private void check() {

        String str = null;
        if (TextUtils.isEmpty(mEtLoginAccount.getText().toString().trim()) || mEtLoginAccount.getText().toString().trim().length() < 11 || !RegexUtils.isMobileExact(mEtLoginAccount.getText().toString().trim())) {
            str = ResourcesUtils.getString(R.string.phone_error);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(str);
            return;
        }
        if (TextUtils.isEmpty(mEtLoginPassword.getText().toString().trim()) || mEtLoginPassword.getText().toString().trim().length() < 8||RegexUtils.isMatch(RegexConstants.ALL_ABC, mEtLoginPassword.getText().toString().trim())||RegexUtils.isMatch(RegexConstants.REGEX_INTEGER, mEtLoginPassword.getText().toString().trim())) {
            str = ResourcesUtils.getString(R.string.password_fail);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(str);
            return;
        }
        if (TextUtils.isEmpty(mEtMessage.getText().toString().trim())) {
            str = ResourcesUtils.getString(R.string.message_code_error);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(str);
            return;
        }
        showDialog();
        NetUtils.getInstance().register(mEtLoginAccount.getText().toString().trim(), mEtLoginPassword.getText().toString().trim(),
                "", mEtMessage.getText().toString().trim(), new NetCallBack() {
                    @Override
                    public void onSuccess(final String message, final int status, String response, final ResultModel model) {
                        closeDialog();
                        if (status == Contants.SUCCESS_CODE) {
                            if (model==null) return;
                            final Register register = model.getModel();
                            LogUtil.e("===" + register.toString());
                            new CustomDialog(RegisterActivity.this)
                                    .setConfirmText(ResourcesUtils.getString(R.string.confirm))
                                    .setContent(ResourcesUtils.getString(R.string.register_success))
                                    .setCanceled(false)
                                    .setOnConfirmClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent(RegisterActivity.this, CompleteInfoActivity.class);
                                            intent.putExtra("id", register.id);
                                            intent.putExtra(Contants.TYPE, 1);
                                            startActivity(intent);
                                            finish();
                                        }
                                    })
                                    .show();
                        } else {
                            if (TextUtils.isEmpty(message)) {
                                return;
                            }
                            Animation shake = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.shake);
                            mTvFail.setVisibility(View.VISIBLE);
                            mTvFail.startAnimation(shake);
                            mTvFail.setText(message);
                        }
                    }

                    @Override
                    public void onFail(String message, int status) {
                        closeDialog();
                    }
                }, Register.class);
    }


    private void senMessage() {
        String str = null;
        if (TextUtils.isEmpty(mEtLoginAccount.getText().toString().trim()) || mEtLoginAccount.getText().toString().trim().length() < 11||!RegexUtils.isMobileExact(mEtLoginAccount.getText().toString().trim())) {
            str = ResourcesUtils.getString(R.string.phone_error);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(str);
            return;
        }
        if (isSend) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(R.string.message_send);
            return;
        }
        NetUtils.getInstance().sms(mEtLoginAccount.getText().toString().trim(), new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, ResultModel model) {
                if (code == 20000) {
                    isSend = true;
                    startTimer();
                } else {
                    isSend = false;
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);

    }

    private void startTimer() {
        mTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mTvSend.setText( millisUntilFinished / 1000 + "s后重新获取");
            }

            @Override
            public void onFinish() {
                isSend = false;
                mTvSend.setText(ResourcesUtils.getString(R.string.send_message_code));
                mTvSend.setClickable(true);
            }
        };
        mTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null)
            mTimer.cancel();
        BitmapDrawable bd = (BitmapDrawable) mRlRoot.getBackground();
        bm = null;
        mRlRoot.setBackgroundDrawable(null);
        bd.setCallback(null);
        bd.getBitmap().recycle();
    }
}
